<template>
  <div class="flowchart-container">
    <!-- 全屏背景图片 -->
    <div class="background-image"></div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <!-- <button
        class="process-button"
        @click="showInfoDialog"
        title="查看流程信息"
      >
        <i class="el-icon-view"></i>
        流程信息
      </button> -->

      <button
        class="process-button"
        @click="showStatusDialog"
        title="查看数据详情"
      >
        <i class="el-icon-data-analysis"></i>
        数据详情
      </button>
    </div>

    <!-- 信息弹窗 -->
    <el-dialog
      title="流程信息"
      :visible.sync="infoDialogVisible"
      width="60%"
      :before-close="handleClose"
    >
      <div class="dialog-content">
        <el-table :data="processInfo" stripe>
          <el-table-column prop="name" label="流程名称" width="200"></el-table-column>
          <el-table-column prop="status" label="状态" width="120">
            <template slot-scope="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="progress" label="进度" width="150">
            <template slot-scope="scope">
              <el-progress :percentage="scope.row.progress" :status="getProgressStatus(scope.row.progress)"></el-progress>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述"></el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="infoDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="refreshData">刷新数据</el-button>
      </span>
    </el-dialog>

    <!-- 状态详情弹窗 -->
    <el-dialog
      title="水质数据详情"
      :visible.sync="statusDialogVisible"
      width="80%"
      :before-close="handleClose"
    >
      <div class="dialog-content">
        <!-- 数据类型切换 -->
        <div class="data-type-tabs">
          <el-radio-group v-model="currentDataType" @change="switchDataType">
            <el-radio-button label="inflow">进水数据</el-radio-button>
            <el-radio-button label="outflow">出水数据</el-radio-button>
          </el-radio-group>
        </div>

        <!-- 加载状态 -->
        <div v-loading="loading" class="water-data-content">
          <div v-if="!loading && waterData && waterData.rtdFields && waterData.rtdFields.length > 0">
            <!-- 数据时间显示 -->
            <div class="data-time-info" v-if="waterData.dataTime">
              <el-alert
                :title="`数据时间: ${formatDataTime(waterData.dataTime)}`"
                type="info"
                :closable="false"
                show-icon
                style="margin-bottom: 20px;">
              </el-alert>
            </div>

            <!-- 实时数据显示 -->
            <el-row :gutter="20">
              <el-col :span="24">
                <el-card class="status-card">
                  <div slot="header" class="card-header">
                    <span>{{ currentDataType === 'inflow' ? '进水' : '出水' }}实时监测数据</span>
                    <el-tag :type="getDataTypeTag(currentDataType)" size="small" style="margin-left: 10px">
                      {{ currentDataType === 'inflow' ? '进水监测' : '出水监测' }}
                    </el-tag>
                  </div>

                  <!-- 使用网格布局显示所有实时数据 -->
                  <el-row :gutter="16">
                    <el-col :span="8" v-for="field in waterData.rtdFields" :key="field.key" style="margin-bottom: 16px;">
                      <div class="rtd-data-item">
                        <div class="rtd-label">{{ field.name }}</div>
                        <div class="rtd-value">
                          {{ field.value }}
                          <span class="rtd-unit" v-if="field.unit">{{ field.unit }}</span>
                        </div>
                      </div>
                    </el-col>
                  </el-row>
                </el-card>
              </el-col>
            </el-row>
          </div>

          <!-- 无数据提示 -->
          <div v-if="!loading && (!waterData || !waterData.rtdFields || waterData.rtdFields.length === 0)" class="no-data">
            <el-empty description="暂无实时监测数据"></el-empty>
          </div>

          <!-- 错误提示 -->
          <div v-if="errorMessage" class="error-message">
            <el-alert
              :title="errorMessage"
              type="error"
              :closable="false"
              show-icon>
            </el-alert>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="statusDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="refreshWaterData" :loading="loading">刷新数据</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getWaterData } from '@/api/wushui/waterData'

export default {
  name: 'FlowChart',
  data() {
    return {
      infoDialogVisible: false,
      statusDialogVisible: false,
      loading: false,
      currentDataType: 'inflow', // 当前数据类型：inflow 进水, outflow 出水
      waterData: null, // 水质数据
      errorMessage: '', // 错误信息
      // 字段名到中文名称的映射
      fieldMapping: {
        'w01001_Rtd': 'PH实时值',
        'w01010_Rtd': '水温实时值(℃)',
        'w21003_Rtd': '氨氮实时值(mg/L)',
        'w00000_Rtd': '流量实时值(mg/L)',
        'w21011_Rtd': '总磷实时值(mg/L)',
        'w01018_Rtd': '化学需氧量实时值(mg/L)',
        'w21001_Rtd': '总氮实时值(mg/L)'
      },
      // 假数据 - 流程信息
      processInfo: [
        {
          name: '进水处理',
          status: '运行中',
          progress: 85,
          description: '原水经过预处理，去除大颗粒杂质'
        },
        {
          name: '混凝沉淀',
          status: '运行中',
          progress: 92,
          description: '添加混凝剂，形成絮体并沉淀'
        },
        {
          name: '过滤处理',
          status: '运行中',
          progress: 78,
          description: '通过砂滤池进一步净化水质'
        },
        {
          name: '消毒处理',
          status: '正常',
          progress: 100,
          description: '加氯消毒，确保出水水质安全'
        },
        {
          name: '出水监测',
          status: '正常',
          progress: 100,
          description: '实时监测出水水质各项指标'
        }
      ]
    }
  },
  methods: {
    showInfoDialog() {
      this.infoDialogVisible = true;
    },
    async showStatusDialog() {
      this.statusDialogVisible = true;
      this.currentDataType = 'inflow'; // 默认显示进水数据
      await this.loadWaterData();
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    getStatusType(status) {
      const statusMap = {
        '运行中': 'primary',
        '正常': 'success',
        '警告': 'warning',
        '故障': 'danger',
        '在线': 'success',
        '离线': 'danger'
      };
      return statusMap[status] || 'info';
    },
    getDataTypeTag(type) {
      return type === 'inflow' ? 'primary' : 'success';
    },
    getProgressStatus(progress) {
      if (progress === 100) return 'success';
      if (progress >= 80) return '';
      if (progress >= 60) return 'warning';
      return 'exception';
    },
    refreshData() {
      this.$message.success('数据已刷新');
      // 这里后续可以调用实际的API接口
    },
    async refreshWaterData() {
      await this.loadWaterData();
    },
    async switchDataType(type) {
      this.currentDataType = type;
      await this.loadWaterData();
    },
    async loadWaterData() {
      this.loading = true;
      this.errorMessage = '';

      try {
        const response = await getWaterData(this.currentDataType);
        if (response.code === 200) {
          console.log('loadWaterData', response)
          // 处理数据，只提取_Rtd结尾的字段
          this.waterData = this.processWaterData(response.data);
        } else {
          this.errorMessage = response.msg || '数据加载失败';
          this.waterData = null;
        }
      } catch (error) {
        console.error('加载水质数据失败:', error);
        this.errorMessage = '网络错误，请检查网络连接';
        this.waterData = null;
        this.$message.error('数据加载失败');
      } finally {
        this.loading = false;
      }
    },
    // 处理水质数据，只提取_Rtd结尾的字段
    processWaterData(rawData) {
      if (!rawData) return null;

      const processedData = {
        dataTime: rawData.dataTime, // 保留数据时间
        rtdFields: [] // 存储处理后的实时数据字段
      };

      // 遍历所有字段，找出_Rtd结尾的字段
      Object.keys(rawData).forEach(key => {
        if (key.endsWith('_Rtd') && rawData[key] !== null && rawData[key] !== undefined) {
          const chineseName = this.fieldMapping[key] || key;
          processedData.rtdFields.push({
            key: key,
            name: chineseName,
            value: rawData[key],
            unit: this.getFieldUnit(key)
          });
        }
      });

      return processedData;
    },
    // 获取字段单位
    getFieldUnit(fieldKey) {
      const unitMapping = {
        'w01001_Rtd': '',
        'w01010_Rtd': '℃',
        'w21003_Rtd': 'mg/L',
        'w00000_Rtd': 'm³/h',
        'w21011_Rtd': 'mg/L',
        'w01018_Rtd': 'mg/L',
        'w21001_Rtd': 'mg/L'
      };
      return unitMapping[fieldKey] || '';
    },
    formatTime(time) {
       if (!time) return '';
       try {
         return new Date(time).toLocaleString('zh-CN');
       } catch (error) {
         return time;
       }
     },
     // 格式化数据时间（处理yyyyMMddHHmmss格式）
     formatDataTime(dataTime) {
       if (!dataTime) return '';
       try {
         // 处理 yyyyMMddHHmmss 格式
         const timeStr = dataTime.toString();
         if (timeStr.length === 14) {
           const year = timeStr.substring(0, 4);
           const month = timeStr.substring(4, 6);
           const day = timeStr.substring(6, 8);
           const hour = timeStr.substring(8, 10);
           const minute = timeStr.substring(10, 12);
           const second = timeStr.substring(12, 14);
           return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
         }
         return dataTime;
       } catch (error) {
         return dataTime;
       }
     }
  }
}
</script>

<style scoped>
.flowchart-container {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.background-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('~@/assets/tlprocess/process.png');
  background-color: #101b33;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  z-index: 1;
}

.action-buttons {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 10;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.process-button {
  padding: 12px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
  min-width: 120px;
  justify-content: center;
}

.process-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}

.process-button:active {
  transform: translateY(0);
}

.process-button i {
  font-size: 16px;
}

.dialog-content {
  max-height: 500px;
  overflow-y: auto;
}

.status-card {
  margin-bottom: 20px;
}

.card-header {
  font-weight: bold;
  color: #303133;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.status-item:last-child {
  border-bottom: none;
}

.status-label {
  font-weight: 500;
  color: #606266;
}

.status-value {
  font-weight: bold;
  color: #409eff;
}

.dialog-footer {
  text-align: right;
}

.data-type-tabs {
  margin-bottom: 20px;
  text-align: center;
}

.water-data-content {
  min-height: 300px;
}

.no-data {
  text-align: center;
  padding: 50px 0;
}

.error-message {
  margin: 20px 0;
}

/* 实时数据项样式 */
.rtd-data-item {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 16px;
  text-align: center;
  transition: all 0.3s ease;
  height: 100%;
}

.rtd-data-item:hover {
  background: #e3f2fd;
  border-color: #2196f3;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(33, 150, 243, 0.15);
}

.rtd-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  font-weight: 500;
}

.rtd-value {
  font-size: 24px;
  font-weight: bold;
  color: #2196f3;
  line-height: 1.2;
}

.rtd-unit {
  font-size: 14px;
  color: #999;
  margin-left: 4px;
  font-weight: normal;
}

/* 数据时间信息样式 */
.data-time-info {
  margin-bottom: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .action-buttons {
    top: 10px;
    right: 10px;
    gap: 10px;
  }

  .process-button {
    padding: 10px 16px;
    font-size: 12px;
    min-width: 100px;
  }

  .background-image {
    background-size: cover;
  }
}

/* 确保弹窗在移动端的显示效果 */
@media (max-width: 768px) {
  .el-dialog {
    width: 95% !important;
    margin: 0 auto !important;
  }
}
</style>
